﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KingRoad.EPM.SafetyManagementEntity.Model;
using KingRoad.EPM.Web.Areas.SafetyConstruction.ViewModels;
using KingRoad.EPM.Web.Areas.SafetyConstruction.SafetyConstructionFramework.Common;

namespace KingRoad.EPM.Web.Areas.SafetyConstruction.Controllers
{
    public class ScmSafeAssessmentController : BaseController
    {
        /// <summary>
        /// 安全考核-列表界面
        /// </summary>
        /// <returns></returns>
        public ActionResult SafeAssessmentList(string pageName)
        {
            var model = new ScmSafetyassessmentViewModel();
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = 1;
            //每页多少条
            ViewBag.numPerPage = 20;
            model.TheSafetyassessmentList = ScmSafetyassessmentUIRule.GetAllSafetyassessmentForPage(ViewBag.pageNum, ViewBag.numPerPage, "Sa_TimeStamp", out totalRecord, "");
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;

            //字典类型列表实体（考核类型）
            model.TheSafetyconstructiondicList = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByPID("BE4758D5-00FE-4A09-8BE8-9F18043FD0F0");
            return String.IsNullOrEmpty(pageName) ? View(model) : View(pageName, model);
        }
        /// <summary>
        /// 安全考核-列表(分页提交)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SplitPage()
        {
            var model = new ScmSafetyassessmentViewModel();
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条
            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);
            if (ViewBag.pageNum == 0 || ViewBag.numPerPage == 0)
                return SafeAssessmentList("SafeAssessmentList");
            ViewBag.iput_title = Request.Form["iput_title"];
            ViewBag.iput_timestart = Request.Form["iput_timestart"];
            ViewBag.iput_timeend = Request.Form["iput_timeend"];
            ViewBag.sel_type = Request.Form["sel_type"];
            string sql = " 1=1 ";
            if (ViewBag.iput_title != "")
                sql += " and Sa_Title like '%" + ViewBag.iput_title + "%' ";
            if (ViewBag.iput_timestart != "")
                sql += " and Sa_AssessmentTime>='" + ViewBag.iput_timestart + "' ";
            if (ViewBag.iput_timeend != "")
                sql += " and Sa_AssessmentTime<='" + ViewBag.iput_timeend + "' ";
            if (ViewBag.sel_type != "")
                sql += " and Scd_ID='" + ViewBag.sel_type + "' ";

            model.TheSafetyassessmentList = ScmSafetyassessmentUIRule.GetAllSafetyassessmentForPage(ViewBag.pageNum, ViewBag.numPerPage, "Sa_TimeStamp", out totalRecord, sql);
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;

            //字典类型列表实体（考核类型）
            model.TheSafetyconstructiondicList = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByPID("BE4758D5-00FE-4A09-8BE8-9F18043FD0F0");
            return View("SafeAssessmentList", model);
        }
        /// <summary>
        /// 安全考核添加（加载添加页面）
        /// </summary>
        /// <returns></returns>
        public ActionResult SafeAssessmentAdd()
        {
            var model = new ScmSafetyassessmentViewModel();
            //安全考核
            model.TheSafetyassessmentInfo = new ScmSafetyassessmentInfo();
            model.TheSafetyassessmentInfo.Sa_ID = Guid.NewGuid().ToString();
            model.TheSafetyassessmentInfo.Sa_AssessmentTime = DateTime.Now;
            model.TheSafetyassessmentInfo.Sa_CreateTime = DateTime.Now;
            model.TheSafetyassessmentInfo.Sa_ModifyTime = DateTime.Now;
            //TODO:当前登录人信息
            model.TheSafetyassessmentInfo.Sa_DepartmentID = GetLoginUserDepartmentId;  //当前登录人所属机构id
            model.TheSafetyassessmentInfo.Sa_DepartmentName = GetLoginUserDepartmentName; //当前登录人所属机构名称
            model.TheSafetyassessmentInfo.Sa_CreateUserID = GetLoginUserId; //当前登录人id
            model.TheSafetyassessmentInfo.Sa_CreateName = GetLoginUserName; //当前登录人名
            model.TheSafetyassessmentInfo.Sa_ModifyUserID = GetLoginUserId; //当前登录人id
            model.TheSafetyassessmentInfo.Sa_ModifyName = GetLoginUserName;  //当前登录人名

            //字典类型列表实体（考核类型）
            model.TheSafetyconstructiondicList = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByPID("BE4758D5-00FE-4A09-8BE8-9F18043FD0F0");
            //监理/施工单位列表
            model.TheUnitList = new List<ProjectUnitInfo>();
            //考核项目列表
            model.TheAssessmentitemsList = ScmAssessmentitemsUIRule.GetAssessmentitemsByType("656B51EF-95AF-4740-9FFA-DCC661A56C3D");
            return View(model);
        }
        /// <summary>
        /// 安全考核添加（信息提交）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SafeAssessmentAdd(ScmSafetyassessmentViewModel mode)
        {
            var aInfo = mode.TheSafetyassessmentInfo;
            var unitCodes = Request.Form["ctgl_kh_section"].Trim(',');
            var del_Items = Request.Form["del_items"].Trim(',');
            var unitList = GetUnitListByCodes(unitCodes);
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                ScmSafetyassessmentUIRule.AddSafetyassessment(aInfo, unitList, del_Items);
            });
            dynamic jsonReturn = new ExpandoObject();
            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "添加成功",
                    navTabId = "SafetyConstruction.ScmSafeAssessment.SafeAssessmentList",
                    rel = "",
                    callbackType = "closeCurrent",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "添加失败",
                };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        /// <summary>
        /// 安全考核项目列表
        /// </summary>
        /// <param name="type">考核类型</param>
        /// <returns></returns>
        public ActionResult SafeAssessmentItems(string type)
        {
            var assessmentitemsList = ScmAssessmentitemsUIRule.GetAssessmentitemsByType(type);
            return PartialView(assessmentitemsList);
        }
        /// <summary>
        /// 安全考核被考核单位弹出框
        /// </summary>
        /// <returns></returns>
        public ActionResult SafeAssessmentUnit()
        {
            return View();
        }
        /// <summary>
        /// 安全考核被考核单位列表
        /// </summary>
        /// <param name="type">考核类型</param>
        /// <param name="ucodes">单位Ids</param>
        /// <returns></returns>
        public ActionResult SafeAssessmentUnitSel(string type, string ucodes)
        {
            //被考核单位的合同号集合
            if (ucodes != null)
                ucodes = ucodes.Trim(',');
            List<ProjectUnitInfo> unitList = GetUnitListByCodes(ucodes);
            return PartialView(unitList);
        }
        /// <summary>
        /// 安全考核修改（加载修改页面）
        /// </summary>
        /// <returns></returns>
        public ActionResult SafeAssessmentEdit(Guid id)
        {
            var model = new ScmSafetyassessmentViewModel();
            //安全考核
            model.TheSafetyassessmentInfo = ScmSafetyassessmentUIRule.GetSafetyassessmentInfo(id);
            model.TheSafetyassessmentInfo.Sa_ModifyTime = DateTime.Now;
            //TODO:当前登录人信息
            model.TheSafetyassessmentInfo.Sa_ModifyUserID = GetLoginUserId;
            model.TheSafetyassessmentInfo.Sa_ModifyName = GetLoginUserRealName;

            //字典类型列表实体（考核类型）
            model.TheSafetyconstructiondicList = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByPID("BE4758D5-00FE-4A09-8BE8-9F18043FD0F0");
            //被选中的单位codes
            string ucodes = "";
            model.TheAssessmentunitList = ScmAssessmentunitUIRule.GetAssessmentunitBySa_ID(model.TheSafetyassessmentInfo.Sa_ID);
            foreach (var info in model.TheAssessmentunitList)
            {
                ucodes += "'" + info.Au_Section + "',";
            }
            ViewBag.ucodes = ucodes;
            ucodes = ucodes.Trim(',');
            string type = model.TheSafetyassessmentInfo.Scd_ID;
            if (type == "1D6426E7-08CB-48F2-B11A-834389148D7C")
                type = "0";
            else
                type = "1";
            //TODO:获取单位信息
            model.TheUnitList = GetUnitListByCodes(ucodes);
            //考核项目列表
            model.TheAssessmentitemsList = ScmAssessmentitemsUIRule.GetAssessmentitemsByType(model.TheSafetyassessmentInfo.Scd_ID);
            //被排除的考核项目Ids
            string del_items = "";
            //被排除的项目集合
            if (model.TheAssessmentunitList.Count>0)
            {
                model.TheAssessmentscoreList = ScmAssessmentscoreUIRule.GetAssessmentscoreBySaAuID(model.TheSafetyassessmentInfo.Sa_ID, model.TheAssessmentunitList[0].Au_ID, "0");
                foreach (var info in model.TheAssessmentscoreList)
                {
                    del_items += info.Ai_ID + ",";
                    var iinfo = model.TheAssessmentitemsList.Find((t) => { return t.Ai_ID == info.Ai_ID; });
                    iinfo.As_Include = false;
                }
            }
            
            ViewBag.del_items = del_items;
            return View(model);
        }
        /// <summary>
        /// 安全考核修改（信息提交）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SafeAssessmentEdit(ScmSafetyassessmentViewModel mode)
        {
            var aInfo = mode.TheSafetyassessmentInfo;
            var ucodes = Request.Form["ctgl_kh_section"].Trim(',');
            var del_Items = Request.Form["del_items"].Trim(',');
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                ScmSafetyassessmentUIRule.EditSafetyassessment(aInfo, GetUnitListByCodes(ucodes), del_Items);
            });
            dynamic jsonReturn = new ExpandoObject();
            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "修改成功",
                    navTabId = "SafetyConstruction.ScmSafeAssessment.SafeAssessmentList",
                    rel = "",
                    callbackType = "closeCurrent",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "修改失败",
                };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        /// <summary>
        /// 考核得分上报
        /// </summary>
        /// <returns></returns>
        public ActionResult SafeAssessmentReport(Guid id)
        {
            var model = new ScmSafetyassessmentViewModel();
            //安全考核
            model.TheSafetyassessmentInfo = ScmSafetyassessmentUIRule.GetSafetyassessmentInfo(id);
            model.TheSafetyassessmentInfo.Sa_ModifyTime = DateTime.Now;
            //TODO:当前登录人信息
            model.TheSafetyassessmentInfo.Sa_ModifyUserID = GetLoginUserId;
            model.TheSafetyassessmentInfo.Sa_ModifyName = GetLoginUserRealName;
            //字典类型列表实体（考核类型）
            model.TheSafetyconstructiondicInfo = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByID(new Guid(model.TheSafetyassessmentInfo.Scd_ID));
            //被考核单位
            model.TheAssessmentunitList = ScmAssessmentunitUIRule.GetAssessmentunitBySa_ID(model.TheSafetyassessmentInfo.Sa_ID);
            return View(model);
        }
        /// <summary>
        /// 考核得分上报（信息提交）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SafeAssessmentReport(ScmSafetyassessmentViewModel mode)
        {
            var aInfo = mode.TheSafetyassessmentInfo;
            aInfo.Sa_State = 1;
            var ulist = mode.TheAssessmentunitList;
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                ScmSafetyassessmentUIRule.ReportSafetyassessment(aInfo, ulist);
            });
            dynamic jsonReturn = new ExpandoObject();
            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "上报成功",
                    navTabId = "SafetyConstruction.ScmSafeAssessment.SafeAssessmentList",
                    rel = "",
                    callbackType = "closeCurrent",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "上报失败",
                };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }

        /// <summary>
        /// 考核分项得分上报
        /// </summary>
        /// <returns></returns>
        public ActionResult SafeAssessmentItemReport(string sa_id, string au_id, string index)
        {
            var model = new ScmSafetyassessmentViewModel();
            model.TheAssessmentscoreList = ScmAssessmentscoreUIRule.GetAssessmentscoreBySaAuID(sa_id, au_id, "1");
            ViewBag.Index = index;
            //获取模块ID
            ViewBag.MoudleID = GetEntityByUrl(Models.PageURL.安全考核);
            //附件目录名
            ViewBag.DirWhere = Models.DirName.安全考核;
            //附件
            var au = ScmAssessmentunitUIRule.GetAssessmentunitInfo(Guid.Parse(au_id));
            if (au.Assist_ID != 0)
            {
                var commonFileList = CommonFileUIRule.GetCommonFilesByConditon(au.Assist_ID, "SafeAssessment_Rules");//SafeKnowledge_Rules  BizType类型
                ViewBag.AssisId = au.Assist_ID;
                ViewBag.FileIds = string.Join(",", commonFileList.Select(t => t.FILE_FILEID));
                ViewBag.DeleteIds = string.Join(",", commonFileList.Select(t => t.FILE_ID));
            }
            else
            {

                var assisId = GenerateRandom();
                var assisIdRet = 0;
                CreateAssistId(ScmAssessmentunitUIRule, assisId, out assisIdRet);
                ViewBag.AssisId = assisIdRet;

            }
            return View(model);
        }
        /// <summary>
        /// 考核分项得分上报（信息提交）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SafeAssessmentItemReport(ScmSafetyassessmentViewModel mode)
        {
            var aInfo = ScmSafetyassessmentUIRule.GetSafetyassessmentInfo(new Guid(mode.TheAssessmentscoreList[0].Sa_ID));
            aInfo.Sa_State = 1;
            //当前登录人信息
            aInfo.Sa_ModifyUserID = GetLoginUserId;
            aInfo.Sa_ModifyName = GetLoginUserRealName;
            var AssistID = Convert.ToInt32(Request.Form["AssistID"]);

            var slist = mode.TheAssessmentscoreList;
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                ScmSafetyassessmentUIRule.ReportSafetyassessmentitem(aInfo, slist, AssistID);
            });
            dynamic jsonReturn = new ExpandoObject();
            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "上报成功",
                    navTabId = "",
                    rel = "",
                    callbackType = "closeCurrent",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "上报失败",
                };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        /// <summary>
        /// 安全考核查看
        /// </summary>
        /// <returns></returns>
        public ActionResult SafeAssessmentDetail(Guid id)
        {
            var model = new ScmSafetyassessmentViewModel();
            //安全考核
            model.TheSafetyassessmentInfo = ScmSafetyassessmentUIRule.GetSafetyassessmentInfo(id);
            //字典类型列表实体（考核类型）
            model.TheSafetyconstructiondicInfo = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByID(new Guid(model.TheSafetyassessmentInfo.Scd_ID));
            //被考核单位
            model.TheAssessmentunitList = ScmAssessmentunitUIRule.GetAssessmentunitBySa_ID(model.TheSafetyassessmentInfo.Sa_ID);
            return View(model);
        }
        /// <summary>
        /// 考核分项得分查看
        /// </summary>
        /// <returns></returns>
        public ActionResult SafeAssessmentItemDetail(string sa_id, string au_id)
        {
            var model = new ScmSafetyassessmentViewModel();
            model.TheAssessmentscoreList = ScmAssessmentscoreUIRule.GetAssessmentscoreBySaAuID(sa_id, au_id, "1");
            //获取模块ID
            ViewBag.MoudleID = GetEntityByUrl(Models.PageURL.安全考核);
            //附件目录名
            ViewBag.DirWhere = Models.DirName.安全考核;

            //附件
            var au = ScmAssessmentunitUIRule.GetAssessmentunitInfo(Guid.Parse(au_id));
            if (au.Assist_ID != 0)
            {
                var commonFileList = CommonFileUIRule.GetCommonFilesByConditon(au.Assist_ID, "SafeAssessment_Rules");//SafeKnowledge_Rules  BizType类型
                ViewBag.AssisId = au.Assist_ID;
                ViewBag.FileIds = string.Join(",", commonFileList.Select(t => t.FILE_FILEID));
                ViewBag.DeleteIds = string.Join(",", commonFileList.Select(t => t.FILE_ID));
            }
            
            return View(model);
        }



        /// <summary>
        /// 安全考核删除
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SafeAssessmentDelete(string ids)
        {
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                ScmSafetyassessmentUIRule.DeleteSafetyassessmentById(ids);
            });
            dynamic jsonReturn = new ExpandoObject();
            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "删除成功！",
                    navTabId = "SafetyConstruction.ScmSafeAssessment.SafeAssessmentList",
                    rel = "",
                    callbackType = "",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "删除失败！",
                };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
    }
}